package com.itphy.socket;

import com.alibaba.fastjson.JSON;
import com.itphy.util.RedisClient;
import org.noear.solon.annotation.ServerEndpoint;
import org.noear.solon.core.message.Listener;
import org.noear.solon.core.message.Message;
import org.noear.solon.core.message.Session;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

//@ServerEndpoint(value = "**")
public class WebSocket implements Listener {
    @Override
    public void onMessage(Session session, Message message) throws IOException {
        Jedis jedis =null;
        try {
            jedis = RedisClient.getJedis();
            String list = jedis.get("wechat::001");
            if(Objects.isNull(list)){
                ArrayList<String> msg = new ArrayList<>();
                msg.add(message.bodyAsString());
                list=JSON.toJSONString(msg);
            }else {
                List<String> o = JSON.parseObject(list, List.class);
                o.add(message.bodyAsString());
                list=JSON.toJSONString(o);
            }//存储时间1分钟
            jedis.setex("wechat::001", 180,list);
            session.getOpenSessions().forEach(s -> {
                s.send(message.bodyAsString());
            });
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(jedis!=null){
                jedis.close();
            }
        }
    }

    @Override
    public void onOpen(Session session) {
        System.out.println("连接socket");
    }

    @Override
    public void onClose(Session session) {
        System.out.println("退出socket");
    }
}
